<template>
  <ManagementLayout title="知识库管理" subtitle="为角色创建和管理知识库">

    <!-- 标签页切换 -->
    <div class="tab-container">
      <el-tabs v-model="currentTab" @tab-change="handleTabChange">
        <el-tab-pane label="角色知识库" name="character">
          <!-- 角色选择 -->
          <div class="character-selector">
            <el-select 
              v-model="selectedCharacterId" 
              placeholder="选择角色"
              @change="loadCharacterKnowledgeDocuments"
              class="character-select"
            >
              <el-option
                v-for="character in characters"
                :key="character.id"
                :label="character.name"
                :value="character.id"
              />
            </el-select>
          </div>

          <!-- 操作按钮 -->
          <div class="action-bar" v-if="selectedCharacterId">
            <el-button 
              type="primary" 
              :icon="Upload" 
              @click="showUploadDialog = true"
              class="upload-button"
            >
              上传文档
            </el-button>
            <el-button 
              type="success" 
              :icon="Link" 
              @click="openLinkDialog"
              class="link-button"
            >
              关联文档
            </el-button>
          </div>

          <!-- 知识库文档列表 -->
          <div class="magic-grid" v-if="selectedCharacterId">
            <ManagementCard 
              v-for="document in knowledgeDocuments" 
              :key="document.id"
              :title="document.title"
              :description="document.description"
              :meta="getDocumentMeta(document)"
            >
              <template #actions>
                <el-button 
                  type="danger" 
                  size="small" 
                  @click="unlinkDocument(document)"
                  :icon="Close"
                >
                  解除关联
                </el-button>
              </template>
            </ManagementCard>
            
            <div v-if="knowledgeDocuments.length === 0" class="empty-state">
              <el-icon size="64" color="#8c939d"><Document /></el-icon>
              <p>该角色暂无关联的知识库文档</p>
              <p>请上传文档或关联现有文档</p>
            </div>
          </div>
        </el-tab-pane>

        <el-tab-pane label="我的文档" name="my">
          <div class="action-bar">
            <el-button 
              type="primary" 
              :icon="Upload" 
              @click="showUploadDialog = true"
              class="upload-button"
            >
              上传文档
            </el-button>
          </div>

          <div class="magic-grid">
            <ManagementCard 
              v-for="document in myDocuments" 
              :key="document.id"
              :title="document.title"
              :description="document.description"
              :meta="getMyDocumentMeta(document)"
            >
              <template #actions>
                <el-button 
                  type="warning" 
                  size="small" 
                  @click="toggleVisibility(document)"
                  :icon="document.is_public ? Lock : Unlock"
                >
                  {{ document.is_public ? '设为私有' : '设为公开' }}
                </el-button>
                <el-button 
                  type="danger" 
                  size="small" 
                  @click="deleteDocument(document)"
                  :icon="Delete"
                >
                  删除
                </el-button>
              </template>
            </ManagementCard>
            
            <div v-if="myDocuments.length === 0" class="empty-state">
              <el-icon size="64" color="#8c939d"><Document /></el-icon>
              <p>暂无知识库文档</p>
              <p>请上传文档</p>
            </div>
          </div>
        </el-tab-pane>

        <el-tab-pane label="公开文档" name="public">
          <div class="magic-grid">
            <ManagementCard 
              v-for="document in publicDocuments" 
              :key="document.id"
              :title="document.title"
              :description="document.description"
              :meta="getPublicDocumentMeta(document)"
            >
              <template #actions>
                <el-button 
                  type="success" 
                  size="small" 
                  @click="linkToCharacter(document)"
                  :icon="Link"
                >
                  关联到角色
                </el-button>
              </template>
            </ManagementCard>
            
            <div v-if="publicDocuments.length === 0" class="empty-state">
              <el-icon size="64" color="#8c939d"><Document /></el-icon>
              <p>暂无公开的知识库文档</p>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 上传文档对话框 -->
    <el-dialog
      v-model="showUploadDialog"
      title="上传知识库文档"
      width="500px"
      class="upload-dialog"
    >
      <el-form :model="uploadForm" label-width="100px">
        <el-form-item label="文档描述">
          <el-input 
            v-model="uploadForm.description" 
            placeholder="请输入文档描述（可选）"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
        <el-form-item label="可见性">
          <el-switch
            v-model="uploadForm.isPublic"
            active-text="公开"
            inactive-text="私有"
          />
        </el-form-item>
      </el-form>
      
      <el-upload
        class="magic-uploader"
        drag
        :before-upload="beforeUpload"
        :http-request="uploadDocument"
        :show-file-list="false"
        :disabled="uploadLoading"
        accept=".pdf,.txt,.docx"
      >
        <el-icon class="el-icon--upload" v-if="!uploadLoading"><upload-filled /></el-icon>
        <el-icon class="el-icon--upload rotating" v-else><Loading /></el-icon>
        <div class="el-upload__text">
          <span v-if="!uploadLoading">将文件拖到此处，或<em>点击上传</em></span>
          <span v-else>正在上传文档，请稍候...</span>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            支持 PDF、TXT、DOCX 格式，文件大小不超过 10MB
          </div>
        </template>
      </el-upload>
    </el-dialog>

    <!-- 关联文档对话框 -->
    <el-dialog
      v-model="showLinkDialog"
      title="关联知识库文档"
      width="700px"
      class="link-dialog"
    >
      <el-tabs v-model="linkTabActive" @tab-change="handleLinkTabChange">
        <el-tab-pane label="我的文档" name="my">
          <div class="link-document-list">
            <div 
              v-for="document in availableMyDocuments" 
              :key="document.id"
              class="link-document-item"
              @click="linkDocument(document)"
            >
              <div class="document-info">
                <h4 class="document-title">{{ document.title }}</h4>
                <p class="document-meta">
                  <span class="document-type">{{ document.source_type }}</span>
                  <span class="created-time">{{ formatTime(document.created_at) }}</span>
                </p>
                <p class="document-description" v-if="document.description">
                  {{ document.description }}
                </p>
              </div>
              <el-button type="primary" size="small" :icon="Link">
                关联
              </el-button>
            </div>
            
            <div v-if="availableMyDocuments.length === 0" class="empty-state">
              <el-icon size="48" color="#8c939d"><Document /></el-icon>
              <p>暂无可关联的文档</p>
            </div>
          </div>
        </el-tab-pane>

        <el-tab-pane label="公开文档" name="public">
          <div class="link-document-list">
            <div 
              v-for="document in availablePublicDocuments" 
              :key="document.id"
              class="link-document-item"
              @click="linkDocument(document)"
            >
              <div class="document-info">
                <h4 class="document-title">{{ document.title }}</h4>
                <p class="document-meta">
                  <span class="document-type">{{ document.source_type }}</span>
                  <span class="creator">创建者: {{ document.creator?.username || '未知' }}</span>
                  <span class="created-time">{{ formatTime(document.created_at) }}</span>
                </p>
                <p class="document-description" v-if="document.description">
                  {{ document.description }}
                </p>
              </div>
              <el-button type="primary" size="small" :icon="Link">
                关联
              </el-button>
            </div>
            
            <div v-if="availablePublicDocuments.length === 0" class="empty-state">
              <el-icon size="48" color="#8c939d"><Document /></el-icon>
              <p>暂无可关联的公开文档</p>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </ManagementLayout>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Upload, Edit, Delete, Document, UploadFilled, Link, Close, Lock, Unlock, Loading } from '@element-plus/icons-vue'
import { 
  getCharacters,
  uploadKnowledgeDocument,
  getMyKnowledgeDocuments,
  getPublicKnowledgeDocuments,
  linkKnowledgeToCharacter,
  unlinkKnowledgeFromCharacter,
  getCharacterKnowledgeDocuments,
  deleteKnowledgeDocument,
  updateKnowledgeDocumentVisibility
} from '@/services/api'
import ManagementLayout from './ManagementLayout.vue'
import ManagementCard from './ManagementCard.vue'
import { 
  formatTime, 
  handleApiError, 
  confirmDelete, 
  confirmAction,
  checkFileType,
  checkFileSize
} from '@/utils/managementUtils'

// 响应式数据
const characters = ref([])
const selectedCharacterId = ref(null)
const knowledgeDocuments = ref([])
const myDocuments = ref([])
const publicDocuments = ref([])
const showUploadDialog = ref(false)
const showLinkDialog = ref(false)
const currentTab = ref('character') // character, my, public
const linkTabActive = ref('my') // 关联对话框的标签页
const availableMyDocuments = ref([]) // 可关联的我的文档
const availablePublicDocuments = ref([]) // 可关联的公开文档
const loading = ref(false) // 通用loading状态
const uploadLoading = ref(false) // 上传loading状态

// 表单数据
const uploadForm = reactive({
  description: '',
  isPublic: true
})

// 加载角色列表
const loadCharacters = async () => {
  try {
    characters.value = await getCharacters()
  } catch (error) {
    ElMessage.error('加载角色列表失败')
  }
}

// 加载角色知识库文档
const loadCharacterKnowledgeDocuments = async () => {
  if (!selectedCharacterId.value) return
  
  try {
    knowledgeDocuments.value = await getCharacterKnowledgeDocuments(selectedCharacterId.value)
  } catch (error) {
    ElMessage.error('加载角色知识库文档失败')
  }
}

// 加载我的文档
const loadMyDocuments = async () => {
  try {
    myDocuments.value = await getMyKnowledgeDocuments()
  } catch (error) {
    ElMessage.error('加载我的文档失败')
  }
}

// 加载公开文档
const loadPublicDocuments = async () => {
  try {
    publicDocuments.value = await getPublicKnowledgeDocuments()
  } catch (error) {
    ElMessage.error('加载公开文档失败')
  }
}

// 标签页切换
const handleTabChange = (tabName) => {
  if (tabName === 'my') {
    loadMyDocuments()
  } else if (tabName === 'public') {
    loadPublicDocuments()
  }
}

// 上传文档
const uploadDocument = async (options) => {
  if (uploadLoading.value) return
  
  uploadLoading.value = true
  try {
    const result = await uploadKnowledgeDocument(
      options.file, 
      uploadForm.description, 
      uploadForm.isPublic
    )
    
    ElMessage.success(`文档"${result.title}"上传成功，已切分为${result.chunks_count}个片段`)
    showUploadDialog.value = false
    uploadForm.description = ''
    uploadForm.isPublic = true
    
    // 刷新当前标签页的数据
    if (currentTab.value === 'my') {
      await loadMyDocuments()
    } else if (currentTab.value === 'public') {
      await loadPublicDocuments()
    }
  } catch (error) {
    console.error('上传文档失败:', error)
    let errorMessage = '上传文档失败'
    
    if (error.message.includes('400')) {
      errorMessage = '文件类型不支持，请上传PDF、TXT或DOCX格式的文件'
    } else if (error.message.includes('413')) {
      errorMessage = '文件过大，请上传小于10MB的文件'
    } else if (error.message.includes('401')) {
      errorMessage = '请先登录后再上传文档'
    } else if (error.message.includes('network')) {
      errorMessage = '网络连接失败，请检查网络后重试'
    }
    
    ElMessage.error(errorMessage)
  } finally {
    uploadLoading.value = false
  }
}

// 解除文档关联
const unlinkDocument = async (document) => {
  try {
    await ElMessageBox.confirm(
      `确定要解除文档"${document.title}"的关联吗？解除后该角色将无法使用此文档的内容。`,
      '确认解除关联',
      {
        confirmButtonText: '解除关联',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    loading.value = true
    await unlinkKnowledgeFromCharacter(selectedCharacterId.value, document.id)
    ElMessage.success(`文档"${document.title}"解除关联成功`)
    await loadCharacterKnowledgeDocuments()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('解除关联失败:', error)
      let errorMessage = '解除关联失败'
      
      if (error.message.includes('400')) {
        errorMessage = '文档未关联到该角色，无需解除关联'
      } else if (error.message.includes('404')) {
        errorMessage = '角色或文档不存在'
      } else if (error.message.includes('401')) {
        errorMessage = '请先登录后再解除关联'
      }
      
      ElMessage.error(errorMessage)
    }
  } finally {
    loading.value = false
  }
}

// 删除文档
const deleteDocument = async (document) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除文档"${document.title}"吗？删除后无法恢复。`,
      '确认删除',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    )
    
    loading.value = true
    await deleteKnowledgeDocument(document.id)
    ElMessage.success(`文档"${document.title}"删除成功`)
    await loadMyDocuments()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除文档失败:', error)
      let errorMessage = '删除文档失败'
      
      if (error.message.includes('403')) {
        errorMessage = '无权限删除此文档，只能删除自己创建的文档'
      } else if (error.message.includes('404')) {
        errorMessage = '文档不存在或已被删除'
      } else if (error.message.includes('401')) {
        errorMessage = '请先登录后再删除文档'
      }
      
      ElMessage.error(errorMessage)
    }
  } finally {
    loading.value = false
  }
}

// 切换文档可见性
const toggleVisibility = async (document) => {
  try {
    const newVisibility = !document.is_public
    const action = newVisibility ? '公开' : '私有'
    
    await ElMessageBox.confirm(
      `确定要将文档"${document.title}"设为${action}吗？`,
      `确认设为${action}`,
      {
        confirmButtonText: `设为${action}`,
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    loading.value = true
    await updateKnowledgeDocumentVisibility(document.id, newVisibility)
    ElMessage.success(`文档"${document.title}"已设为${action}`)
    await loadMyDocuments()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('更新文档可见性失败:', error)
      let errorMessage = '更新文档可见性失败'
      
      if (error.message.includes('403')) {
        errorMessage = '无权限修改此文档，只能修改自己创建的文档'
      } else if (error.message.includes('404')) {
        errorMessage = '文档不存在或已被删除'
      } else if (error.message.includes('401')) {
        errorMessage = '请先登录后再修改文档'
      }
      
      ElMessage.error(errorMessage)
    }
  } finally {
    loading.value = false
  }
}

// 关联文档到角色
const linkToCharacter = async (document) => {
  if (!selectedCharacterId.value) {
    ElMessage.warning('请先选择角色')
    return
  }
  
  try {
    await linkKnowledgeToCharacter(selectedCharacterId.value, document.id)
    ElMessage.success('文档关联成功')
    await loadCharacterKnowledgeDocuments()
  } catch (error) {
    ElMessage.error('关联文档失败')
  }
}

// 关联对话框中的关联文档
const linkDocument = async (document) => {
  if (!selectedCharacterId.value) {
    ElMessage.warning('请先选择角色')
    return
  }
  
  try {
    loading.value = true
    await linkKnowledgeToCharacter(selectedCharacterId.value, document.id)
    ElMessage.success(`文档"${document.title}"关联成功`)
    showLinkDialog.value = false
    await loadCharacterKnowledgeDocuments()
    await loadAvailableDocuments() // 重新加载可关联的文档
  } catch (error) {
    console.error('关联文档失败:', error)
    let errorMessage = '关联文档失败'
    
    if (error.message.includes('400')) {
      errorMessage = '文档已关联到该角色，无需重复关联'
    } else if (error.message.includes('403')) {
      errorMessage = '无权限关联此文档，只能关联公开文档或自己创建的文档'
    } else if (error.message.includes('404')) {
      errorMessage = '角色或文档不存在'
    } else if (error.message.includes('401')) {
      errorMessage = '请先登录后再关联文档'
    }
    
    ElMessage.error(errorMessage)
  } finally {
    loading.value = false
  }
}

// 关联对话框标签页切换
const handleLinkTabChange = (tabName) => {
  if (tabName === 'my') {
    loadAvailableMyDocuments()
  } else if (tabName === 'public') {
    loadAvailablePublicDocuments()
  }
}

// 加载可关联的我的文档（排除已关联的）
const loadAvailableMyDocuments = async () => {
  try {
    const allMyDocs = await getMyKnowledgeDocuments()
    const linkedDocs = knowledgeDocuments.value
    availableMyDocuments.value = allMyDocs.filter(doc => 
      !linkedDocs.some(linked => linked.id === doc.id)
    )
  } catch (error) {
    ElMessage.error('加载可关联文档失败')
  }
}

// 加载可关联的公开文档（排除已关联的）
const loadAvailablePublicDocuments = async () => {
  try {
    const allPublicDocs = await getPublicKnowledgeDocuments()
    const linkedDocs = knowledgeDocuments.value
    availablePublicDocuments.value = allPublicDocs.filter(doc => 
      !linkedDocs.some(linked => linked.id === doc.id)
    )
  } catch (error) {
    ElMessage.error('加载可关联文档失败')
  }
}

// 加载所有可关联的文档
const loadAvailableDocuments = async () => {
  await loadAvailableMyDocuments()
  await loadAvailablePublicDocuments()
}

// 打开关联对话框
const openLinkDialog = async () => {
  if (!selectedCharacterId.value) {
    ElMessage.warning('请先选择角色')
    return
  }
  
  showLinkDialog.value = true
  linkTabActive.value = 'my'
  await loadAvailableDocuments()
}

// 上传前检查
const beforeUpload = (file) => {
  const allowedTypes = ['application/pdf', 'text/plain', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document']
  const isAllowedType = allowedTypes.includes(file.type)
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isAllowedType) {
    ElMessage.error('只支持 PDF、TXT、DOCX 格式的文件!')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过 10MB!')
    return false
  }
  return true
}

// 获取文档元信息
const getDocumentMeta = (document) => {
  const meta = [document.source_type]
  meta.push(formatTime(document.created_at))
  return meta
}

const getMyDocumentMeta = (document) => {
  const meta = [document.source_type]
  meta.push(document.is_public ? '公开' : '私有')
  meta.push(formatTime(document.created_at))
  return meta
}

const getPublicDocumentMeta = (document) => {
  const meta = [document.source_type]
  meta.push(`创建者: ${document.creator?.username || '未知'}`)
  meta.push(formatTime(document.created_at))
  return meta
}

// 组件挂载时加载数据
onMounted(() => {
  loadCharacters()
})
</script>

<style scoped>
@import '@/styles/management-common.css';

.character-selector {
  margin-bottom: 30px;
  text-align: center;
}

.character-select {
  width: 300px;
}

.upload-button {
  background: linear-gradient(135deg, #D4AF37, #FFD700);
  border: none;
  color: #2C1810;
  font-weight: 600;
  margin-right: 10px;
}

.link-button {
  background: linear-gradient(135deg, #4CAF50, #66BB6A);
  border: none;
  color: #fff;
  font-weight: 600;
}

/* 关联对话框特有样式 */
.link-dialog {
  color: #F7F3E9;
}

.link-document-list {
  max-height: 400px;
  overflow-y: auto;
  padding: 10px 0;
}

.link-document-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  margin-bottom: 10px;
  background: rgba(0, 0, 0, 0.3);
  border: 1px solid rgba(212, 175, 55, 0.5);
  border-radius: 8px;
  cursor: pointer;
}

.link-document-item:hover {
  background: rgba(0, 0, 0, 0.5);
  border-color: #D4AF37;
  box-shadow: 0 2px 8px rgba(212, 175, 55, 0.3);
}

.link-document-item .document-info {
  flex: 1;
  margin-right: 15px;
}

.link-document-item .document-title {
  color: #FFD700;
  font-size: 16px;
  font-weight: 600;
  margin: 0 0 8px 0;
}

.link-document-item .document-meta {
  color: #D4AF37;
  font-size: 12px;
  margin: 0 0 8px 0;
}

.link-document-item .document-meta span {
  margin-right: 10px;
}

.link-document-item .document-description {
  color: #F7F3E9;
  font-size: 13px;
  line-height: 1.4;
  margin: 0;
  opacity: 0.8;
}
</style>

